package com.example.fruitdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.fruitdemo.pojo.User;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.alibaba.druid.sql.ast.TDDLHint.Type.JSON;

@RestController
@RequestMapping("/api")
public class RegisterController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public R<Object> register(@Validated @RequestBody User user, BindingResult result, HttpServletResponse response) {
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                String msg = item.getDefaultMessage();
                String field = item.getField();
                map.put(field, msg);
            });
            //System.out.println(map);
            Object err = JSONObject.toJSON(map);
            return R.Err(err);
        }
        return userService.register(user, response);
    }
    @PostMapping("/resetpwd")
    public R<Object> resetpwd(@Validated @RequestBody User user, BindingResult result, HttpServletResponse response) {
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                String msg = item.getDefaultMessage();
                String field = item.getField();
                map.put(field, msg);
            });
            //System.out.println(map);
            Object err = JSONObject.toJSON(map);
            return R.Err(err);
        }
        return userService.resetpwd(user, response);
    }
}

